package com.topdt.jbpm.service.cmd;

import java.util.Date;

import org.jbpm.api.TaskQuery;
import org.jbpm.api.task.Task;

import com.thx.common.util.ThreadLocalContext;
import com.topdt.jbpm.model.HistTodo;
import com.topdt.jbpm.model.Todo;


/**  
 *  @Project       : saasoa
 *  @Program Name  : com.topdt.jbpm.service.cmd.GoOtherBackWorkCmd.java
 *  @Class Name    : GoOtherBackWorkCmd
 *  @Description   : 退回某个环节
 *  @Author        : calonlan
 *  @Creation Date : 2015年1月5日 下午5:22:26 
 *  @ModificationHistory  
 *  Who        When          What 
 *  --------   ----------    -----------------------------------
 *  username   2015年1月5日       TODO
 */
public class GoOtherBackWorkCmd extends JumpWorkCmd{

	
	public GoOtherBackWorkCmd(String todoId) {
		this.todoId = todoId;
	}
	
	@Override
	protected JumpResult doExecute() {
		creatResult();
		//找到要退回的环节和历史处理人
		getToTask();
		//退回任务
		completeTask();
		
		return result;
	}
	
	protected void completeTask() {
		if (toActivity != null && histTodos != null) {
			String users = "";
			for (HistTodo todo : histTodos) {
				users = users + todo.getToUser() + ",";
			}

			if (users.endsWith(","))
				users = users.substring(0, users.length() - 1);

			getDestUsers();
			
			taskVars.put(toActivity.getName() + "_assginee", users);
			
			if(superTask!=null){
				taskService.completeTask(task.getId());
				taskService.completeTask(superTask.getId(), outCome, taskVars);	
			}else{
				taskService.completeTask(task.getId(), outCome, taskVars);					
			}

			jbpmService.getTodoDao().delete(todoId);

			HistTodo hTodo = new HistTodo(todo);
			hTodo.setState(Todo.STATE_BACK);// 退回去了
			hTodo.setDestActivityName(toActivity.getName());
			hTodo.setFinishTime(new Date());
			jbpmService.getHistTodoDao().save(hTodo);

			work.setCurActivityName("[" + toActivity.getName() + ":" + this.destUsers.get(0).getName() + "]");
			jbpmService.getWorkDao().update(work);
			//要退回历史环节的待办没有执行getNextCircs()方法，没有执行"ThreadLocalContext.remove("next_circs");"
			//造成退回来以后在线程变量中还有要退回历史环节的信息
			ThreadLocalContext.remove("next_circs");
			
			defaultResult();
		} else {
			creatResult();
			result.setJumpAble(false);
		}
	}

}
